<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 加载状态 -->
    <div v-if="loading" class="flex justify-center items-center py-12">
      <UIcon name="i-heroicons-arrow-path" class="h-8 w-8 animate-spin text-primary-600" />
    </div>

    <div v-else>
      <!-- 个人信息区域 -->
      <div class="bg-white shadow-sm">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div class="flex items-start space-x-6">
            <!-- 头像和基本信息 -->
            <div class="flex-shrink-0">
              <UAvatar
                size="2xl"
                :src="userInfo?.avatar"
                :ui="{ background: 'bg-primary-100' }"
              />
            </div>
            <div class="flex-1">
              <div class="flex items-center justify-between">
                <div>
                  <h1 class="text-2xl font-bold text-gray-900">{{ userInfo?.nickname || userInfo?.username }}</h1>
                  <div class="flex items-center mt-1 mb-1">
                    <UBadge color="gray" variant="subtle" size="sm" class="flex items-center space-x-1">
                      <UIcon name="i-heroicons-identification" class="h-3 w-3" />
                      <span>ID: {{ userInfo?.id }}</span>
                    </UBadge>
                    <!-- 性别展示 -->
                    <UBadge v-if="userInfo?.gender" 
                      :color="userInfo?.gender === 'M' ? 'blue' : 'pink'" 
                      variant="subtle" 
                      size="sm" 
                      class="flex items-center space-x-1 ml-2 px-2 py-1 rounded-full">
                      <UIcon :name="userInfo?.gender === 'M' ? 'i-heroicons-user-circle' : 'i-heroicons-heart'" class="h-3 w-3" />
                      <span>{{ userInfo?.gender === 'M' ? '男' : '女' }}</span>
                    </UBadge>
                  </div>
                  <p class="mt-1 text-sm text-gray-500">{{ userInfo?.description }}</p>
                </div>
                <div class="flex items-center space-x-3">
                  <!-- 关注/取消关注按钮 -->
                  <UButton 
                    v-if="!isCurrentUser" 
                    :color="isFollowing ? 'gray' : 'primary'" 
                    :variant="isFollowing ? 'soft' : 'solid'" 
                    class="flex items-center space-x-1 transition-all duration-300 transform hover:scale-105" 
                    @click="toggleFollow"
                  >
                    <UIcon :name="isFollowing ? 'i-heroicons-user-minus' : 'i-heroicons-user-plus'" class="h-4 w-4" />
                    <span>{{ isFollowing ? '取消关注' : '关注' }}</span>
                  </UButton>
                  <!-- 编辑资料按钮 -->
                  <UButton 
                    v-if="isCurrentUser" 
                    color="primary" 
                    class="flex items-center space-x-1" 
                    @click="navigateTo('/user/edit-profile')"
                  >
                    <UIcon name="i-heroicons-pencil" class="h-4 w-4" />
                    <span>编辑资料</span>
                  </UButton>
                </div>
              </div>
              
              <!-- 统计数据 -->
              <div class="mt-6 flex items-center space-x-12">
                <div class="flex flex-col items-center">
                  <span class="text-2xl font-bold text-gray-900">{{ userInfo?.artboardCount || 0 }}</span>
                  <span class="text-sm text-gray-500">作品</span>
                </div>
                <div class="flex flex-col items-center">
                  <span class="text-2xl font-bold text-gray-900">{{ userInfo?.followerCount || 0 }}</span>
                  <span class="text-sm text-gray-500">粉丝</span>
                </div>
                <div class="flex flex-col items-center">
                  <span class="text-2xl font-bold text-gray-900">{{ userInfo?.attentionCount || 0 }}</span>
                  <span class="text-sm text-gray-500">关注</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 功能导航 -->
      <div class="border-b border-gray-200 bg-white">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div class="flex space-x-8">
            <button class="flex items-center space-x-2 py-4 border-b-2 border-primary-500 text-primary-600">
              <UIcon name="i-heroicons-squares-2x2" class="h-5 w-5" />
              <span>画板</span>
            </button>
          </div>
        </div>
      </div>

      <!-- 画板列表 -->
      <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- 添加新建画板按钮 -->
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-xl font-semibold text-gray-900">我的画板</h2>
          <UButton 
            color="primary" 
            icon="i-heroicons-plus" 
            @click="showCreateModal = true"
            class="flex items-center space-x-1"
          >
            新建画板
          </UButton>
        </div>
        
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          <div 
            v-for="board in boards" 
            :key="board.id" 
            class="bg-white rounded-lg shadow-sm overflow-hidden hover:shadow-md transition-shadow duration-200"
            @mouseenter="board.showUploadOverlay = true"
            @mouseleave="board.showUploadOverlay = false"
          >
            <div class="relative aspect-w-16 aspect-h-10">
              <!-- 上传图片浮动窗口 -->
              <div 
                v-show="board.showUploadOverlay" 
                class="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center z-10 transition-opacity duration-200"
              >
                <div class="text-center">
                  <UButton color="white" variant="solid" class="flex flex-col items-center p-4">
                    <UIcon name="i-heroicons-arrow-up-tray" class="h-8 w-8" />
                    <span class="mt-2">上传图片</span>
                  </UButton>
                </div>
              </div>
              
              <template v-if="board.images && board.images.length > 0">
                <!-- 2张图片布局 -->
                <div v-if="board.images.length === 2" class="grid grid-cols-2 h-full w-full gap-1">
                  <div v-for="(image, index) in board.images" :key="image.id" class="relative overflow-hidden h-full">
                    <NuxtImg 
                      :src="image.img_url" 
                      :alt="`${board.title} - ${index + 1}`" 
                      class="object-cover w-full h-full" 
                      loading="lazy" 
                      placeholder 
                    />
                  </div>
                </div>
                <!-- 3张图片布局 -->
                <div v-else-if="board.images.length === 3" class="grid grid-cols-3 h-full w-full gap-2 p-2">
                  <div v-for="(image, index) in board.images" :key="image.id" class="relative overflow-hidden aspect-square">
                    <NuxtImg 
                      :src="image.img_url" 
                      :alt="`${board.title} - ${index + 1}`" 
                      class="object-cover w-full h-full rounded-lg" 
                      loading="lazy" 
                      placeholder 
                    />
                  </div>
                </div>
                <!-- 4张及以上图片布局 -->
                <div v-else-if="board.images.length > 3" class="grid grid-cols-2 grid-rows-2 h-full w-full gap-1">
                  <div v-for="(image, index) in board.images.slice(0, 4)" :key="image.id" class="relative overflow-hidden">
                    <NuxtImg 
                      :src="image.img_url" 
                      :alt="`${board.title} - ${index + 1}`" 
                      class="object-cover w-full h-full" 
                      loading="lazy" 
                      placeholder 
                    />
                    <div v-if="index === 3 && board.images.length > 4" class="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
                      <span class="text-white font-medium">+{{ board.images.length - 4 }}</span>
                    </div>
                  </div>
                </div>
                <!-- 单图布局 -->
                <NuxtImg v-else :src="board.images[0]?.img_url" :alt="board.title" class="object-cover w-full h-full" loading="lazy" placeholder />
              </template>
              <template v-else>
                <div class="w-full h-full flex flex-col items-center justify-center bg-gray-100">
                  <UIcon name="i-heroicons-photo" class="h-12 w-12 text-gray-400" />
                  <p class="mt-2 text-sm text-gray-500">该画板暂无图片</p>
                </div>
              </template>
            </div>
            <div class="p-4">
              <div class="flex items-center space-x-2 mb-2">
                <h3 class="text-lg font-medium text-gray-900 flex-1 cursor-pointer hover:text-primary-600" @click="navigateToBoard(board.id)">{{ board.title }}</h3>
                <span class="text-sm text-primary-600 bg-primary-50 px-2 py-1 rounded-full flex items-center">
                  <UIcon name="i-heroicons-fire" class="h-4 w-4 text-orange-500 mr-1" />
                  <span>{{ board.hotness }}</span>
                </span>
              </div>
              <p class="text-sm text-gray-500 mb-3">{{ board.description }}</p>
              <div class="text-xs text-gray-400 space-x-2 mb-4">
                <UBadge v-for="tag in board.tags.split(',')" :key="tag" color="secondary"  variant="subtle" size="sm" class="inline-block">
                  <span class="text-gray-600">{{ tag.trim() }}</span>
                </UBadge>
              </div>
              <div class="flex items-center justify-between text-sm text-gray-500">
                <div class="flex items-center space-x-4">
                  <span class="flex items-center space-x-1">
                    <UIcon name="i-heroicons-eye" class="h-5 w-5" />
                    <span>{{ board.images[0]?.views_count || 0 }}</span>
                  </span>
                  <span class="flex items-center space-x-1">
                    <UIcon name="i-heroicons-arrow-down-tray" class="h-5 w-5" />
                    <span>{{ board.images[0]?.download_count || 0 }}</span>
                  </span>
                </div>
                <span>{{ formatDate(board.images[0]?.created_at || 0) }}</span>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
    
    <!-- 引入新建画板模态框组件 -->
    <CreateBoardModal v-model="showCreateModal" @created="refreshBoards" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { userApi, type Board, type UserInfo } from '~/utils/user'
import { api } from '~/utils/api'

const loading = ref(true)
const userInfo = ref<UserInfo | null>(null)
const boards = ref<Board[]>([])  
const error = ref<string | null>(null)
const showCreateModal = ref(false)
const isFollowing = ref(false)
const isCurrentUser = ref(true) // 默认为当前用户自己的页面

// 获取用户个人信息
const fetchUserInfo = async () => {
  try {
    const response = await api.get('/api/v1/users/me')
    const data = response
    if (data.code === 0) {
      userInfo.value = data.data
    } else {
      error.value = '获取用户信息失败'
    }
  } catch (e) {
    error.value = '网络请求错误'
  }
}

// 获取用户画板数据
const fetchUserBoards = async () => {
  try {
    const data = await userApi.getUserBoards()
    if (data) {
      boards.value = data
    } else {
      error.value = '获取数据失败'
    }
  } catch (e) {
    error.value = '网络请求错误'
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (timestamp: number) => {
  const date = new Date(timestamp)
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
}

// 导航到画板详情页
const navigateToBoard = (boardId: number) => {
  navigateTo(`/board/${boardId}`)
}

// 刷新画板列表
const refreshBoards = async () => {
  await fetchUserBoards()
}

// 关注/取消关注用户
const toggleFollow = async () => {
  try {
    const endpoint = isFollowing.value ? '/api/v1/users/unfollow' : '/api/v1/users/follow'
    const response = await api.post(endpoint, { userId: userInfo.value?.id })
    
    if (response.code === 0) {
      isFollowing.value = !isFollowing.value
      
      // 更新关注数据
      if (userInfo.value) {
        if (isFollowing.value) {
          userInfo.value.followerCount++
        } else {
          userInfo.value.followerCount--
        }
      }
      
      // 显示成功提示
      useToast().add({
        title: isFollowing.value ? '关注成功' : '已取消关注',
        color: isFollowing.value ? 'green' : 'gray',
        position: 'top'
      })
    } else {
      // 显示错误提示
      useToast().add({
        title: '操作失败',
        description: response.msg || '请稍后重试',
        color: 'red',
        position: 'top'
      })
    }
  } catch (error) {
    console.error('关注操作失败:', error)
    useToast().add({
      title: '操作失败',
      description: error instanceof Error ? error.message : '请稍后重试',
      color: 'red',
      position: 'top'
    })
  }
}

// 检查是否已关注该用户
const checkFollowStatus = async () => {
  if (!isCurrentUser.value && userInfo.value?.id) {
    try {
      const response = await api.get(`/api/v1/users/follow/status?userId=${userInfo.value.id}`)
      if (response.code === 0) {
        isFollowing.value = response.data.isFollowing
      }
    } catch (error) {
      console.error('获取关注状态失败:', error)
    }
  }
}

onMounted(async () => {
  try {
    // 并行请求用户信息和画板数据
    await Promise.all([fetchUserInfo(), fetchUserBoards()])
    
    // 检查是否是当前用户自己的页面
    const route = useRoute()
    const userId = route.params.id
    isCurrentUser.value = !userId || userId === userInfo.value?.id
    
    // 如果不是当前用户自己的页面，检查关注状态
    if (!isCurrentUser.value) {
      await checkFollowStatus()
    }
  } catch (e) {
    error.value = '加载数据失败'
    loading.value = false
  }
})
</script>
